package net.hctek.identity.action;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

import javax.servlet.ServletContext;




public class SocketThread extends Thread{

private ServletContext servletContext;
	
	private ServerSocket serverSocket;
	
	private static BufferedReader bufferedReader;
	
	public static HashMap<String,Socket> socketList = new HashMap<>();
	public static String channelToken;
	
	public SocketThread(ServerSocket serverSocket,ServletContext servletContext){
		this.servletContext = servletContext;
		String prot = this.servletContext.getInitParameter("socketPort");
		if(serverSocket == null){
			try {
				this.serverSocket = new ServerSocket(Integer.parseInt(prot));
				System.out.println("serverSocket:"+this.serverSocket.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void run(){
		while(!this.isInterrupted()){
			try {
				Socket socket = serverSocket.accept();
				bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				channelToken = bufferedReader.readLine();
				socketList.put(channelToken,socket);
				
				System.out.println("socketList.get:"+socketList.get(channelToken).toString());
				System.out.println("socketList:"+socketList.values());

				if(socket != null ){
					
					new ProcessSocketData(socket,this.servletContext,socketList.get(channelToken).toString()).start();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void closeServerSocket(){
		try {
			if(serverSocket != null && !serverSocket.isClosed()){
				serverSocket.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}
